Grokking Microsoft Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Microsoft Easy Problems
Buddy Strings (easy)
Solution: Buddy Strings
Can Place Flowers (easy)
Solution: Can Place Flowers
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Maximum Number of Balloons (easy)
Solution: Maximum Number of Balloons
Binary Tree Path Sum (easy)
Solution: Binary Tree Path Sum
Pair with Target Sum (easy)
Solution: Pair with Target Sum
Buy Two Chocolates (easy)
Solution: Buy Two Chocolates
Root Equals Sum of Children (easy)
Solution: Root Equals Sum of Children
Excel Sheet Column Title (easy)
Solution: Excel Sheet Column Title
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Min Cost Climbing Stairs (easy)
Solution: Min Cost Climbing Stairs
Plus One (easy)
Solution: Plus One
Intersection of Two Arrays (easy)
Solution: Intersection of Two Arrays
Find the Index of the First Occurrence in a String (easy)
Solution: Find the Index of the First Occurrence in a String
Merge Two Sorted Lists (easy)
Solution: Merge Two Sorted Lists
Nth Digit (medium)
Solution: Nth Digit
Restore IP Addresses (medium)
Solution: Restore IP Addresses
Find Original Array From Doubled Array (medium)
Solution: Find Original Array From Doubled Array
Reverse Words in a String II (medium)
Solution: Reverse Words in a String II
Longest Arithmetic Subsequence (medium)
Solution: Longest Arithmetic Subsequence
Matchsticks to Square (medium)
Solution: Matchsticks to Square
Score of Parentheses (medium)
Solution: Score of Parentheses
Maximum Length of a Concatenated String with Unique Characters (medium)
Solution: Maximum Length of a Concatenated String with Unique Characters
Inorder Successor in BST (medium)
Solution: Inorder Successor in BST
Distribute Coins in Binary Tree (medium)
Solution: Distribute Coins in Binary Tree
Spiral Matrix (medium)
Solution: Spiral Matrix
Delete Node in a BST (medium)
Solution: Delete Node in a BST
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Rotate Image (medium)
Solution: Rotate Image
Combinations (medium)
Solution: Combinations
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Multiply Strings (medium)
Solution: Multiply Strings
Best Time to Buy and Sell Stock II (medium)
Solution: Best Time to Buy and Sell Stock II
Largest Palindromic Number (medium)
Solution: Largest Palindromic Number
Remove Duplicate Letters (medium)
Solution: Remove Duplicate Letters
Next Permutation (medium)
Solution: Next Permutation
132 Pattern (medium)
Solution: 132 Pattern
Valid Sudoku (medium)
Solution: Valid Sudoku
Number of Islands (medium)
Solution: Number of Islands
Buildings With an Ocean View (medium)
Solution: Buildings With an Ocean View
Regular Expression Matching (hard)
Solution: Regular Expression Matching
First Missing Positive (hard)
Solution: First Missing Positive
Largest Rectangle in Histogram (hard)
Solution: Largest Rectangle in Histogram
Sliding Window Maximum (hard)
Solution: Sliding Window Maximum
Count Unique Characters of All Substrings of a Given String (hard)
Solution: Count Unique Characters of All Substrings of a Given String
Word Ladder (hard)
Solution: Word Ladder
Word Ladder II (hard)
Solution: Word Ladder II
Number of Flowers in Full Bloom (hard)
Solution: Number of Flowers in Full Bloom
Median of Two Sorted Arrays (hard)
Solution: Median of Two Sorted Arrays
Longest Valid Parentheses (hard)
Solution: Longest Valid Parentheses
Solution: Pair with Target Sum

Problem Statement

Given an array of numbers sorted in ascending order and a target sum, find a pair in the array whose sum is equal to the given target. If no such pair exists return [-1, -1].

Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target.

Example 1:

Input: [1, 2, 3, 4, 6], target=6
Output: [1, 3]
Explanation: The numbers at index 1 and 3 add up to 6: 2+4=6

Example 2:

Input: [2, 5, 9, 11], target=11
Output: [0, 2]
Explanation: The numbers at index 0 and 2 add up to 11: 2+9=11

Constraints:

  • 2 <= arr.length <= 104
  • -109 <= arr[i] <= 109
  • -109 <= target <= 109

Solution

Since the given array is sorted, a brute-force solution could be to iterate through the array, taking one number at a time and searching for the second number through Binary Search. The time complexity of this algorithm will be . Can we do better than this?

To solve this problem, we can use a two-pointer approach. This approach is efficient because it takes advantage of the sorted nature of the array. By starting with one pointer at the beginning and the other at the end, we can adjust their positions based on the sum of the elements they point to. This allows us to find the pair that adds up to the target without needing to check all possible pairs, which saves time.

By moving the pointers inward, we can systematically find the pair in a single pass through the array. This ensures that the solution is both time-efficient and easy to implement.

Step-by-Step Algorithm

  • Initialize two pointers: Start with one pointer (left) at the beginning (index 0) and the other pointer (right) at the end (last index) of the array.
  • Loop until pointers meet: Continue the loop until left is less than right.
    • Calculate current sum: Add the elements at the left and right pointers.
    • Check if the sum matches the target:
      • If currentSum equals the target sum, return the indices [left, right].
      • If currentSum is less than the target sum, increment the left pointer to increase the sum.
      • If currentSum is more than the target sum, decrement the right pointer to decrease the sum.
  • Return default values: If no pair is found, return [-1, -1].

Algorithm Walkthrough

Let's walk through the example with input [1, 2, 3, 4, 6] and target 6.

  • Initialize pointers: left = 0, right = 4
  • First iteration:
    • currentSum = 1 + 6 = 7 (greater than target)
    • Decrement right to 3
  • Second iteration:
    • currentSum = 1 + 4 = 5 (less than target)
    • Increment left to 1
  • Third iteration:
    • currentSum = 2 + 4 = 6 (equals target)
    • Return indices [1, 3]

Here is the visual representation of this algorithm for Example-1:

Image

Code

Here is what our algorithm will look like:

Java
Saved to Cloud

. . . .

Time Complexity

  1. Initialization: Constant time, , as it involves assigning values to left and right.

  2. While Loop:

    • The while loop runs as long as left is less than right.
    • In the worst case, this loop iterates over all elements of the array once. This happens when no pair is found, or the pair is found at the extreme ends of the array.
    • Each iteration involves a constant amount of work: calculating currentSum, comparing it with targetSum, and then incrementing left or decrementing right.

    Therefore, the loop runs in time, where is the number of elements in the array.

  3. Overall: The dominant factor in this algorithm is the while loop, making the overall time complexity .

Space Complexity

  • The algorithm uses a fixed amount of extra space: variables left, right, and currentSum.
  • It does not depend on the size of the input array, as no additional data structures are used that grow with the input size.
  • Thus, the space complexity is , constant space.

In summary, the algorithm has a time complexity of and a space complexity of .

An Alternate approach

Instead of using a two-pointer or a binary search approach, we can utilize a HashTable to search for the required pair. We can iterate through the array one number at a time. Let’s say during our iteration we are at number ‘X’, so we need to find ‘Y’ such that “”. We will do two things here:

Search for ‘Y’ (which is equivalent to “Target−X”) in the HashTable. If it is there, we have found the required pair. Otherwise, insert “X” in the HashTable, so that we can search it for the later numbers.

Step-by-step Algorithm

  1. Initialize a HashMap:

    • Create a HashMap to store numbers as keys and their indices as values.
  2. Iterate through the array:

    • Loop through each element in the array using a for loop.
  3. Check for the complement:

    • For each element, check if the HashMap contains the complement (i.e., targetSum - current element).
    • If it does, return the indices of the complement and the current element.
  4. Store the element and its index:

    • If the complement is not found, store the current element and its index in the HashMap.
  5. Return result:

    • If no pair is found by the end of the loop, return [-1, -1].

Algorithm Walkthrough

Example Input: [1, 2, 3, 4, 6], Target: 6

  1. Initialize:

    • nums = {}
  2. First iteration (i = 0):

    • Current element: 1
    • Complement needed: 6 - 1 = 5
    • 5 is not in nums
    • Store 1 with index 0: nums = {1: 0}
  3. Second iteration (i = 1):

    • Current element: 2
    • Complement needed: 6 - 2 = 4
    • 4 is not in nums
    • Store 2 with index 1: nums = {1: 0, 2: 1}
  4. Third iteration (i = 2):

    • Current element: 3
    • Complement needed: 6 - 3 = 3
    • 3 is not in nums
    • Store 3 with index 2: nums = {1: 0, 2: 1, 3: 2}
  5. Fourth iteration (i = 3):

    • Current element: 4
    • Complement needed: 6 - 4 = 2
    • 2 is in nums with index 1
    • Return indices [1, 3]

Code

Java
Saved to Cloud

. . . .

Time Complexity

  1. HashMap Initialization: Constant time, .

  2. For Loop:

    • The for loop iterates over each element of the array once.
    • In each iteration, the algorithm checks if the element is already present in the HashMap (or dictionary in Python) and either returns a result or inserts an element into the HashMap.
    • This element checking or insertion operations of a HashMap generally operate in time due to efficient hashing. However, in the worst case (e.g., when many hash collisions occur), these operations can degrade to . Under the assumption of a good hash function with minimal collisions, these operations can be considered .

    Therefore, the loop runs in time in the average case, where (n) is the number of elements in the array.

  3. Overall: The dominating factor in this algorithm is the for loop. Under the assumption of efficient hashing, the overall average time complexity is .

Space Complexity

  • The algorithm uses a HashMap to store elements from the array. In the worst case, this map can store all elements of the array if no pair is found that adds up to the target sum
  • Thus, the space complexity is proportional to the number of elements in the array, which is .

In summary, the algorithm has an average time complexity of and a space complexity of . The time complexity can degrade to in the worst case due to potential hash collisions, but this is generally not the common case with a good hash function.

Pair with Target Sum (easy)
Buy Two Chocolates (easy)
Mark as Completed

On this page

Problem Statement

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Time Complexity

Space Complexity

An Alternate approach

Step-by-step Algorithm

Algorithm Walkthrough

Code

Time Complexity

Space Complexity